package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.MemberListAdapter;
import com.gem.taskplan.service.BackAcitvity;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.JsonPackage;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AddTeamActivity extends Activity {

	private SharedPreferences sharedPreferences;       //得到保存的信息
	private String curUserName;
//	private TextView teamProjectName = null;   //上一个activity传过来的项目名
	private TextView userName = null;			//当前用户
	private ImageView back = null;				//返回按钮
	private ListView addUserListView = null;  //团队成员listview
	private ListView teamMembers = null;  //被选中成员listview
	private MemberListAdapter memberListAdapter1 = null;//团队成员适配器
	private MemberListAdapter memberListAdapter2 = null;//团队成员适配器
	private ImageView addTeamMember;//关联成员按钮
	private View addMemberView;//添加成员的布局视图
	private ImageView addTeamFinish;
	private LayoutInflater inflater;
	private List<Map<String, String>> list1 = null;
	private List<Map<String, String>> list2 = null;
	private Set<String> setStrings = new TreeSet<String>();//用来存储被关联的成员名字
	private EditText teamName = null;						//团队的名称
	StringBuffer buffer = null;
	private String[] memberName;
	private String url = "/SetServlet";
	private String edit;
	String receiveTeamName;
	private static String urlHead = "/ProjectServlet";//查询项目路径
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_team);
		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);
		
		/************获得访问服务器的地址***************/
		url = PropertiesUtil.getServerURL(this)+url;
		urlHead = PropertiesUtil.getServerURL(this)+urlHead;
		
		/************************************/
		inflater = getLayoutInflater();
		userName = (TextView) findViewById(R.id.userName);
//		teamProjectName = (TextView) findViewById(R.id.teamProjectName);
		back = (ImageView) findViewById(R.id.backImage);
		addTeamMember = (ImageView) findViewById(R.id.addTeam_members);
		teamMembers = (ListView) findViewById(R.id.teamMembers);
		addTeamFinish = (ImageView) findViewById(R.id.addTeamFinish);
		teamName = (EditText) findViewById(R.id.teamName);
		sharedPreferences = AddTeamActivity.this.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE);
		curUserName = sharedPreferences.getString("lastUser", "");
		userName.setText(curUserName);
		addTeamMember.setOnClickListener(new ImageAddMemberOnclick());
		list1 = new ArrayList<Map<String,String>>();
		list2 = new ArrayList<Map<String,String>>();
		memberListAdapter1 = new MemberListAdapter(list1, AddTeamActivity.this, R.layout.choose_member_list);
		memberListAdapter2 = new MemberListAdapter(list2, AddTeamActivity.this, R.layout.choose_member_list2);
		teamMembers.setAdapter(memberListAdapter2);
		addTeamFinish.setOnClickListener(new addTeamFinishSetOnClickListener());
		Intent intent = getIntent();
		if(intent!=null){
			receiveTeamName = intent.getStringExtra("teamName");
			edit = intent.getStringExtra("edit");
			teamName.setText(receiveTeamName);
			System.out.println("传过来的团队名："+receiveTeamName);
			initTeamMember(receiveTeamName);
			init();
			for (int i = 0; i < list2.size(); i++) {
				for (int j = 0; j < list1.size(); j++) {
					if (list2.get(i).get("name").equals(list1.get(j).get("name"))) {
						Map<String, String> map = list1.get(j);
						map.put("checked", "1");
						setStrings.add(String.valueOf(j));
						list1.set(j,map);
					}
				}
			}
			memberListAdapter1.notifyDataSetChanged();
		}else {
			init();
		}
		BackAcitvity.back(back, AddTeamActivity.this);
		/*******初始化*******/
	}
	/******************完成团队添加监听事件***********************/
	private class addTeamFinishSetOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {

			String teamNameString = teamName.getText().toString();
			if (teamNameString.length()==0) {
				Toast.makeText(AddTeamActivity.this, "请您给一个团队名！", Toast.LENGTH_SHORT).show();
				return;
			}else if(list2.size()==0){
				Toast.makeText(AddTeamActivity.this, "关联成员不能为空！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String addTeamName = teamName.getText().toString();
			getIntent().putExtra("addTeamName", teamName.getText().toString());
			String[] memberName= new String[list2.size()+1];
			String[] memberKey = new String[list2.size()+1];
			memberName[0] = curUserName;
			memberKey[0] = "user_name";
			for (int i = 0; i < list2.size(); i++) {
				memberName[i+1] = list2.get(i).get("name");
				memberKey[i+1] = "user_name";
			}
			String jsonsString = JsonPackage.getJson("userInfo", memberName, memberKey);
			System.out.println(list2.size()+"**************jsons字符串："+jsonsString);
			Map<String, String> map = new HashMap<String, String>();
			map.put("teamName", teamNameString);
			map.put("members", jsonsString);
			if (edit!=null&&edit.equals("edit")) {
				map.put("oldTeam", receiveTeamName);
				map.put("action","editTeam");
			}else {
				map.put("action", "addTeam");
			}
			
			/*********判断是否联网***************/
			if(!CheckedNetWork.checkedConnection(AddTeamActivity.this)){
				return;
			}
			
			String result = null;
			try {
				result = HttpUtil.postRequest(url, map);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("########################:"+result);
			if (result.equals("yes")) {
				if (edit!=null&&edit.equals("edit")) {
					Toast.makeText(AddTeamActivity.this, "团队修改成功！", Toast.LENGTH_SHORT).show();
				}else {
					Toast.makeText(AddTeamActivity.this, "创建团队成功！", Toast.LENGTH_SHORT).show();
				}
				Intent data = new Intent(AddTeamActivity.this, WorkTableActivity.class);
				data.putExtra("TeamName", teamNameString);
				setResult(2, data);
				finish();
			}else {
//				Toast.makeText(AddTeamActivity.this, "请求服务器添加团队失败！", Toast.LENGTH_SHORT).show();
			}
			
		}
		
	}

	/******************关联成员按钮的监听***********************/
	public class ImageAddMemberOnclick implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			System.out.println("进入 关联成员按钮的监听");
			addMemberView = inflater.inflate(R.layout.base_user_dialog, null);
			addUserListView = (ListView) addMemberView.findViewById(R.id.userList);
			addUserListView.setAdapter(memberListAdapter1);
			System.out.println(curUserName);
			
			//成员列表addUserListView的监听
			addUserListView.setOnItemClickListener(new AddTeamMemberOnItemClick());
			//弹出成员选择的窗口
			new AlertDialog.Builder(AddTeamActivity.this).setView(addMemberView).
			setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					System.out.println("set集合 = "+setStrings.size());
					list2.clear();
					for(String member :setStrings){
						int position = Integer.parseInt(member);
						Map<String, String> map = list1.get(position);
						list2.add(map);
					}
					memberListAdapter2.notifyDataSetChanged();
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			}).create().show();
		}
	}
	/************************成员列表addUserListView的监听*****************************/
	public class AddTeamMemberOnItemClick implements AdapterView.OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			System.out.println("进入成员列表addUserListView的监听");
			ImageView imageView =  (ImageView) view.findViewById(R.id.choosed1);
			Map<String, String> map = null;
			//String name = list.get(position).get("name");
			map = list1.get(position);
			if(imageView.getVisibility()==View.VISIBLE){
				imageView.setVisibility(View.INVISIBLE);
				map.put("checked", "0");
				setStrings.remove(String.valueOf(position));
			}else {
				imageView.setVisibility(View.VISIBLE);
				map.put("checked", "1");
				setStrings.add(String.valueOf(position));
			}
			list1.set(position, map);
			memberListAdapter1.notifyDataSetChanged();//刷新listView
		}
	}
	
	//初始化代码
	public void init(){
		
		/*********判断是否联网***************/
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("user_name", curUserName);
		map1.put("action", "queryUser");
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			System.out.println("*********"+array.length());
			list1.clear();
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				System.out.println("*********"+array2.length());
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
					System.out.println("####"+map.get("url"));
				}else {
					map.put("url",url);
					System.out.println("####"+map.get("url"));
				}
				map.put("name", name);
				map.put("checked", "0");
				System.out.println("####"+map.get("name"));
				list1.add(map);
			}
			//请求当前用户头像
			Map<String, String> map = new HashMap<String, String>();
			map.put("userName", curUserName);
			map.put("action", "getHead");
			String resultString = null;
			try {
				resultString = HttpUtil.postRequest(urlHead, map);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if(resultString==null){
				return;
			}
			System.out.println("addTeamActivity界面：用户头像路径"+resultString);
			Map<String , String> map2 = new HashMap<String, String>();
			if (resultString.length() == 0) {
				map2.put("url","");
				System.out.println("####"+map2.get("url"));
			}else {
				map2.put("url",resultString);
				System.out.println("####"+map2.get("url"));
			}
			map2.put("name", curUserName);
			map2.put("checked", "0");
			list1.add(0,map2);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		memberListAdapter1.notifyDataSetChanged();
	}
	//初始化代码
	public void initTeamMember(String team){
		/*********判断是否联网***************/
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		
		System.out.println("*********编辑团队");
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("action", "queryTeamMember");
		map1.put("teamName", team);
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("已经创建好的团队result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			System.out.println("*********"+array.length());
			list2.clear();
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				System.out.println("*********"+array2.length());
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
					System.out.println("####"+map.get("url"));
				}else {
					map.put("url",url);
					System.out.println("####"+map.get("url"));
				}
				map.put("name", name);
//				map.put("checked", "1");
				System.out.println("####"+map.get("name"));
				list2.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		System.out.println("刷新数据（（（（（（（（（（（（（（（（）））））））））））））））））））））））");
		//刷新数据
		memberListAdapter2.notifyDataSetChanged();
	}
	
}
